<template>
  <van-nav-bar :title="showSn == 1 ? t('outbound.pickInfo') : t('outbound.outboundInfo')" left-arrow @click-left="onClickLeft" @click-right="showPrinter = true" placeholder fixed>
    <template v-if="showSn == 2" #right>
      <van-icon name="printer" size="22" />
    </template>
  </van-nav-bar>
  <van-cell-group v-if="showSn == 2 && !loading" class="px-5 py-2">
    <van-row class="van-cell__title">{{ t('outbound.customer') + currentOrder.customerCode }}</van-row>
    <van-row class="van-cell__title">{{ t('outbound.outboundNo') + currentOrder.orderNo }}</van-row>
    <van-row class="van-cell__title">{{ t('outbound.providerNo') + currentOrder.providerTrackingNo }}</van-row>
    <van-row class="van-cell__title">{{ t('outbound.providerChannel') + currentOrder.providerChannelName }}</van-row>
  </van-cell-group>
  <van-field ref="skuCodeRef" v-model="skuCode" size="large" @keydown.enter="handleScanSku" :placeholder="t('outbound.pleaseScanSku')" clearable>
    <template #left-icon>
      <van-icon name="enlarge" size="1.5rem" class="px-2"/>
    </template>
  </van-field>
  <div v-if="showSn == 1">
    <van-row class="px-5 py-2">
      <van-col span="24" class="text-right">
      <span class="van-highlight__tag" @click="showProvider = true">
      {{ t('outbound.provider') }}
    </span>
      </van-col>
    </van-row>
    <van-cell-group>
      <van-empty v-if="finished && orderList?.length <= 0" :description="t('noData')"/>
      <van-list v-else v-model:loading="loading" :finished="finished" :loading-text="t('loading')" @load="onLoad" >
        <van-row class="p-5 van-hairline--surround" v-for="(item, i) in orderList" :key="i" @click="choose(item)">
          <van-col span="24">{{ t('outbound.outboundNo') + item.orderNo }}</van-col>
          <van-col span="24">{{ t('outbound.providerNo') + item.providerTrackingNo }}</van-col>
          <van-col span="24">{{ t('outbound.providerChannel') + item.providerChannelName }}</van-col>
        </van-row>
      </van-list>
    </van-cell-group>
  </div>
  <div v-if="showSn == 2">
    <van-collapse v-model="currentSkuIndex" accordion>
      <van-collapse-item v-for="(sku, i) in currentOrder.outboundOrderGraspingCodeGoodsList" :key="i" :name="i">
        <template #title>
          <span class="font-bold">{{ sku.skuCode }}</span>
        </template>
        <van-cell-group class="text-center p-2">
          <van-row>
            <van-col span="12">{{ t('outbound.outboundNum') }}</van-col>
            <van-col span="12">{{ t('outbound.scanNum') }}</van-col>
          </van-row>
          <van-row class="mt-1 font-bold">
            <van-col span="12">
              <van-field center readonly input-align="center" :model-value="sku.goodsNum" style="font-size: xx-large" />
            </van-col>
            <van-col span="6" offset="3">
              <van-field center input-align="center" :max="parseInt(sku.goodsNum)" type="digit" @keydown.enter="handleSkuNum" v-model="sku.realNum" class="input-border">
              </van-field>
            </van-col>
          </van-row>
        </van-cell-group>
      </van-collapse-item>
    </van-collapse>
    <van-field :label="t('outbound.photo')" required label-align="top">
      <template #input>
        <van-uploader v-model="fileList" multiple :max-count="3" />
      </template>
    </van-field>
    <van-action-bar placeholder>
      <van-row gutter="10" class="w-full p-1">
        <van-col span="24">
          <van-button class="text-base" block type="primary" @click="confirmOutbound">{{ t('outbound.outboundConfirm') }}</van-button>
        </van-col>
      </van-row>
    </van-action-bar>
  </div>
  <van-back-top />
  <van-popup v-model:show="showProvider" position="bottom">
    <van-picker :confirm-button-text="t('confirm')" :cancel-button-text="t('outbound.reset')"  v-model="selectedProvider" :title="t('outbound.selectProvider')" :columns="providerList" @confirm="selectProvider" @cancel="resetProvider" />
  </van-popup>
  <van-popup v-model:show="showPrinter" position="bottom">
    <van-picker :confirm-button-text="t('confirm')" :cancel-button-text="t('cancel')" v-model="selectedPrinter" :title="t('outbound.selectPrinter')" :columns="printerList" @confirm="selectPrinter" @cancel="showPrinter = false; printing = false" />
  </van-popup>

  <van-action-sheet v-model:show="showAction" :title="t('outbound.outboundConfirm')">
    <van-form @submit="onSubmitOutbound">
      <van-cell-group inset>
        <van-field ref="providerNoRef"
                   :rules="[{ validator, message: t('outbound.pleaseScanProviderNo') }]"
                   v-model="providerNo"
                   submit-on-enter
                   clearable
                   :placeholder="t('outbound.pleaseScanProviderNo')"
        >
          <template #left-icon>
            <van-icon class="mr-2" name="enlarge" size="20"/>
          </template>
        </van-field>
      </van-cell-group>
      <div class="m-2">
        <van-button :loading="confirmLoading" block type="primary" native-type="submit">
          {{ t('confirm') }}
        </van-button>
      </div>
    </van-form>
  </van-action-sheet>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { postRequest, scanSuccess, scanFail } from "@/api";
import { useRoute } from "vue-router";
import { AppToast } from "@/utils/appToast";
import { localStorage } from "@/utils/local-storage";
import { STORAGE_PRINTER_KEY } from "@/stores/mutation-type";
import { getPrinter, printUrl } from "@/utils/print";
import { showSuccessToast } from "vant";
import { nextTick } from "vue";

const query = useRoute().query;
const { t } = useI18n();
const onClickLeft = () => {
  showSn.value -= 1
  nextTick(() => skuCodeRef.value.focus())
  if(!showSn.value) {
    history.back();
  }
}

const showSn = ref(1);
const orderList : any = ref([]);
const allOrderList = ref([]);
const providerList = ref([]);
const printerList = ref([]);
const finished = ref(false);
const showProvider = ref(false);
const showAction = ref(false);
const selectedProvider = ref([]);
const showPrinter = ref(false);
const printing = ref(false);
const selectedPrinter = ref([]);
const skuCode = ref();
const skuCodeRef = ref();
const providerNo = ref();
const providerNoRef = ref();
const provider = ref();

const loading = ref(true);
const confirmLoading = ref(false);
const currentOrder: any = ref({});
const fileList = ref([]);

const currentSkuIndex = ref(0);

onMounted(() => {
  skuCodeRef.value.focus()
  onLoad()
  getPrinter((res) => {
        printerList.value = res.data.map(item => {
          return {
            value: item,
            text: item,
          }
        })
      },
      (res) => {
        AppToast(t('outbound.loadPrinterError')+" "+res.message,"danger");
      }
  );

})

const onLoad = () => {
  postRequest("/outbound/outBoundOrder/getSiCode", { siCode: query.orderNo }).then(res => {
    allOrderList.value = res.data.orderList.filter(item => item.orderStatus === 2)
    orderList.value = allOrderList.value
    providerList.value = Array.from(new Set(res.data.orderList.map(item => item.providerChannelName))).map(item => {
      return { text: item, value: item }
    });
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  }).finally(() => {
    finished.value = true;
  })
};

const selectProvider = ({ selectedOptions }) => {
  showProvider.value = false;
  finished.value = false;
  loading.value = true;
  provider.value = selectedOptions[0]?.text
  orderList.value = provider.value ? allOrderList.value.filter(item => item.providerChannelName === provider.value) : allOrderList
  loading.value = false;
  finished.value = true;
}

const resetProvider = () => {
  showProvider.value = false;
  finished.value = false;
  loading.value = true;
  provider.value = null
  orderList.value = allOrderList.value
  loading.value = false;
  finished.value = true;
}

const selectPrinter = ({ selectedOptions }) => {
  const value = selectedOptions[0]?.value;
  localStorage.set(STORAGE_PRINTER_KEY, value);
  showPrinter.value = false;
  if (value && printing.value) {
    print()
  }
}

const handleScanSku = () => {
  if (showSn.value == 1) {
    const order = allOrderList.value.find(item => item.outboundOrderPackageGoodsList.find(sku => sku.skuCode.toLowerCase() === skuCode.value.toLowerCase()))
    if (order) {
      currentOrder.value = order
      const sku = order.outboundOrderGraspingCodeGoodsList.find(item => item.skuCode.toLowerCase() === skuCode.value.toLowerCase())
      if (parseInt(sku.realNum || 0) < sku.goodsNum) {
        scanSuccess()
        sku.realNum = parseInt(sku.realNum || 0) + 1
        handleSkuNum()
      } else {
        scanFail();
      }
      showDetail()
    } else {
      scanFail();
    }
  } else if (showSn.value == 2) {
    const index = currentOrder.value.outboundOrderGraspingCodeGoodsList.findIndex(sku => sku.skuCode.toLowerCase() === skuCode.value.toLowerCase())
    if (index >= 0) {
      currentSkuIndex.value = index
      const sku = currentOrder.value.outboundOrderGraspingCodeGoodsList[index]
      if (parseInt(sku.realNum || 0) < sku.goodsNum) {
        scanSuccess()
        sku.realNum = parseInt(sku.realNum || 0) + 1
        handleSkuNum()
      } else {
        scanFail();
      }
    } else {
      scanFail();
    }
  }
  skuCode.value = null
};

const showDetail = () => {
  showSn.value = 2
  skuCode.value = null
  providerNo.value = null
  fileList.value = []
  nextTick(() => skuCodeRef.value.focus())
}

const choose = (order) => {
  currentOrder.value = order
  currentSkuIndex.value = 0
  showDetail()
}


const handleSkuNum = () => {
  if (currentOrder.value.outboundOrderGraspingCodeGoodsList.find(item => item.goodsNum <= item.realNum)) {
    showSuccessToast(t("outbound.autoPrinter"));
    print()
  }
}

const print = () => {
  printing.value = true
  printUrl(currentOrder.value.providerTrackingNoUrl,
      () => {
        AppToast(t("outbound.printerSuccess"), "success")
      },
      (res) => {
        AppToast(t("outbound.printerError") + res || "", "danger")
      },
      () => {
        showPrinter.value = true
      }, () => {
        printing.value = false
      }
  );
}

const confirmOutbound = () => {
  for (let i = 0; i < currentOrder.value.outboundOrderGraspingCodeGoodsList.length; i++) {
    const sku = currentOrder.value.outboundOrderGraspingCodeGoodsList[i]
    if (sku.goodsNum !== parseInt(sku.realNum)) {
      currentSkuIndex.value = i
      AppToast(t("pleaseCheckRequired"), "danger", true);
      confirmLoading.value = false
      return
    }
  }
  if (fileList.value.length <= 0) {
    AppToast(t("pleaseCheckRequired"), "danger", true);
    confirmLoading.value = false
    return
  }
  showAction.value = true
  nextTick(() => providerNoRef.value.focus());
}

const validator = (value) => {
  providerNo.value = null;
  return value === currentOrder.value.providerTrackingNo
}

const onSubmitOutbound = () => {
  confirmLoading.value = true
  const formData: FormData = new FormData()
  formData.set('orderId', currentOrder.value.orderId);
  formData.set("outerPackage",fileList.value[0]?.file);
  formData.set("productPackage",fileList.value[1]?.file);
  formData.set('productPhoto', fileList.value[2]?.file);
  postRequest('/outbound/outBoundOrder/setOutboundOrderStatusPackById', formData).then(() => {
    AppToast(t("outbound.outboundSuccess"), "success")
    allOrderList.value.splice(allOrderList.value.indexOf(currentOrder.value), 1);
    orderList.value = provider.value ? allOrderList.value.filter(item => item.providerChannelName === provider.value) : allOrderList.value
    showAction.value = false
    showSn.value = 1
    nextTick(() => skuCodeRef.value.focus())
  }).finally(() => {
    confirmLoading.value = false
  })
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-collapse-item__content) {
  padding: 0;
}

:deep(.input-border) {
  border: 1px solid #e5e7eb;
  font-size: xx-large;
}
</style>
